package com.yzycoc.hamster.demo.time202505.time20250528.test;

import com.alibaba.fastjson2.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.AuthorizeSecurityGroupRequest;
import com.aliyuncs.ecs.model.v20140526.AuthorizeSecurityGroupResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
 * 创建时间： 2025/5/12
 *
 * @version 1.0
 **/
public class AddEcsWhiteList {


    // 请替换为你的AccessKey信息
    static String accessKeyId = "LTAI5tGR1iXVa12LN5j3G7mc";
    static String accessKeySecret = "gIaaZcRvlmxJRDArIDWTrqusH63RfO";

    // 请替换为你的地域ID
    static String regionId = "cn-hangzhou";
    // 请替换为你的安全组ID
    static String securityGroupId = "sg-bp14ggqzi9k50xltku8u";
    // 请替换为你要添加的IP地址段，例如 "192.168.1.0/24"
    static String ipProtocol = "tcp";
    // 请替换为你要添加的端口范围，例如 "80" 或 "80/8080"
    static String portRange = "1/65535";
    // 请替换为你的IP
    static String sourceCidrIp = "115.230.250.106";
    static String desc = "嘉兴jd办公IP";


    public static void main(String[] args) {
        sourceCidrIp = GetIp.getNetworkIp();
        ecsAddWhiteList();
    }

    private static void ecsAddWhiteList() {

        // 创建一个默认的客户端配置
        IClientProfile profile = DefaultProfile.getProfile(
                regionId,
                accessKeyId,
                accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        AuthorizeSecurityGroupRequest request = new AuthorizeSecurityGroupRequest();
        request.setRegionId(regionId);
        request.setSecurityGroupId(securityGroupId);
        request.setIpProtocol(ipProtocol);
        request.setPortRange(portRange);
        request.setSourceCidrIp(sourceCidrIp);
        request.setDescription(desc);

        try {
            AuthorizeSecurityGroupResponse response = client.getAcsResponse(request);
            System.out.println("添加白名单成功，请求ID：" + response.getRequestId());
            System.out.println("添加结果："+ JSON.toJSONString(response));
        } catch (ClientException e) {
            System.out.println("添加白名单失败，错误信息：" + e.getMessage());
        }
    }

}